import alimt20181012, * as $alimt20181012 from "@alicloud/alimt20181012"
import * as $OpenApi from "@alicloud/openapi-client"
import {isObject,chunk} from 'lodash-es'
function AliyunTranslate(aliyunConfig) {
  this.client = null;
  this.createClient = async () => {
    // if(this.client) return this.client;
    let config = new $OpenApi.Config({})
    config.accessKeyId = aliyunConfig.accessKeyId
    config.accessKeySecret = aliyunConfig.accessKeySecret
    config.regionId = 'cn-hangzhou'
    return new alimt20181012.default(config)
    // 1. 初始化配置
  }
  /**
   * 批量翻译文本
   * @param {string|object} value  需要翻译的内容
   * @param {object} parames  语言参数
   * @param {string} parames.from  源语言标识
   * @param {string} parames.to  目标语言标识
   * @param {'title'|'description'|'communication'|'medical'|'social'|'finance'} [parames.Scene] 专业版必传  场景 商品标题（title），商品描述（description），商品沟通（communication），医疗（medical），社交（social)，金融（finance）
   * @param {boolean} isProfessional 是否专业版
   */
  this.batchTranslate = async (value, parames = { from: "zh", to: "en" },isProfessional) => {
    let client = await this.createClient()
    let keys = Object.keys(value)
    let result = {};
    if(!keys.length) return {}
    //待翻译的条数不能超过 50 单条翻译字符数不能超过 1000 字符
    let chunksKey = chunk(keys,50) //切分为长度为50的二维数组
    for (let i = 0; i < chunksKey.length; i++) {
      let chunkKey = chunksKey[i];
      let temp = {};
      for (let j = 0; j < chunkKey.length; j++) {
        let key = chunkKey[j];
        temp[key] = value[key]
      }
      let request = new $alimt20181012.GetBatchTranslateRequest({
        apiType:isProfessional?'translate_ecommerce':'translate_standard',
        formatType: 'text',
        scene:!isProfessional?'general':(parames.scene||'title'),
        sourceLanguage: parames.from,
        targetLanguage: parames.to,
        sourceText: JSON.stringify(temp)
      })
      let response = await client.getBatchTranslate(request)
      if(response.body.code == 200){
        let translatedList = response.body.translatedList
        for (let index = 0; index < translatedList.length; index++) {
          const obj = translatedList[index];
          result[obj.index] = obj.translated
        }
      }
    }
    return result;
  }


  /**
   *
   * @param {string|object} value  需要翻译的内容
   * @param {object} parames  语言参数
   * @param {string} parames.from  源语言标识
   * @param {string} parames.to  目标语言标识
   * @param {'title'|'description'|'communication'|'medical'|'social'|'finance'} [parames.Scene] 专业版必传  场景 商品标题（title），商品描述（description），商品沟通（communication），医疗（medical），社交（social)，金融（finance）
   * @param {boolean} isProfessional 是否专业版
   * @returns
   */
  this.translate = async (value, parames = { from: "zh", to: "en" }, isProfessional = false) => {
    if(isObject(value)){
      return await this.batchTranslate(value, parames,isProfessional)
    }
    let client = await this.createClient()
    let query = {
      formatType: 'text',
      sourceLanguage: parames.from,
      targetLanguage: parames.to,
      sourceText: value
    }
    if (isProfessional) {
      query.scene = parames.Scene || 'title'
    }
    let request = new $alimt20181012[isProfessional ? 'TranslateRequest' : 'TranslateGeneralRequest'](query)
    let response = await client.translateGeneral(request)
    if (response.body.code != 200) {
      throw new Error(response.body.message)
    }
    return response.body.data.translated
  }
  return this.translate;
}

export default AliyunTranslate;
